package com.wangl.generator.wlmybatisgenerator.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 *
 * @author wangl
 */
public class ZipUtil {

    /**
     *
     * @param file 要压缩的文件
     * @param zipFile 压缩文件存放地方
     */
    public static void zip(File file, FileOutputStream zipFile) {
        try(ZipOutputStream outputStream = new ZipOutputStream(zipFile)) {
            outputStream.setEncoding("UTF-8");
            zipFile(outputStream, file, "");
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     *
     * @param output ZipOutputStream对象
     * @param file 要压缩的文件或文件夹
     * @param basePath 条目根目录
     */
    private static void zipFile(ZipOutputStream output, File file, String basePath) {
        FileInputStream input = null;
        try {
            // 文件为目录
            if (file.isDirectory()) {
                // 得到当前目录里面的文件列表
                File list[] = file.listFiles();
                basePath = basePath + (basePath.length() == 0 ? "" : "/")
                        + file.getName();
                // 循环递归压缩每个文件
                for (File f : list) {
                    zipFile(output, f, basePath);
                }
            } else {
                // 压缩文件
                basePath = (basePath.length() == 0 ? "" : basePath + "/")
                        + file.getName();
                output.putNextEntry(new ZipEntry(basePath));
                input = new FileInputStream(file);
                int readLen = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
                    output.write(buffer, 0, readLen);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            // 关闭流
            if (input != null) {
                try {
                    input.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}